package net.dreamlu.qa.model;

import java.util.Date;
import java.util.List;

import net.dreamlu.util.TimeUtil;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;

/**
 * 用户信息Model
 * @author lcm
 */
public class User extends Model<User> {
	private static final long serialVersionUID = 1L;
	public static final User dao = new User();
	
	// 添加用户的统一处理
	public void addUser(User user){
		user.set("reg_time", new Date()).set("create_time", new Date()).set("update_time", new Date()).save();
	}
	// 更新用户的统一处理
	public void updateUser(User user){
		user.set("update_time", new Date()).update();
	}
	
	// 获取用户关联的问题
	public List<Question> getQuestions (){
		return Question.dao.find("select * from question where user_id = ? and del_status =0 order by id desc", get("id"));
	}
	
	// 获取用户关联的问题  分页版 1|size
	public List<Question> getQuestPage (int size){
		Page<Question> page = Question.dao.paginate(1, size, "select * ", "from question where user_id = ? and del_status =0 order by id desc", get("id"));
		return page.getList();
	}
	
	// 获取用户关联的回答
	public List<Answer> getAnswers (){
		return Answer.dao.find("select * from answer where answer_uid = ? and del_status =0 order by id desc", get("id"));
	}
	
	// 获取用户关联的回答  分页版 1|size
	public List<Answer> getAnswersPage (int size){
		Page<Answer> page = Answer.dao.paginate(1, size, "select * ", "from answer where user_id = ? and del_status =0 order by id desc", get("id"));
		return page.getList();
	}
	
	// 获取多少天前加入
	public String getTimeGo(){
		return TimeUtil.getGoTime(getTimestamp("reg_time"));
	}
	
	// 根据用户名模糊查询 page
	public Page<User> getLikePage(int pageNum, int pageSize, String like) {
		return User.dao.paginate(pageNum, pageSize, "select * ", "from user_info where login_name like '%"+ like +"%' and del_status =0 order by id desc");
	} 
	
	// 根据用户名模糊查询 count
	public Integer getLikeCount(String like) {
		Long count = Db.queryLong("select count(1) from user_info where login_name like '%"+ like +"%' and del_status =0");
		return count == null ? 0 : count.intValue();
	}
	
	/**
	 * 获取用户的问题数目
	 * *使用Db 直接 get("id") 获取 为 null*
	 */
	public Integer getUQuestCount(User user){
		Long count = Db.queryLong("select count(1) from question where user_id = ? and del_status =0", user.get("id"));
		return count == null ? 0 : count.intValue();
	}
	
	/**
	 * 获取用户的回答数目
	 * *使用Db 直接 get("id") 获取 为 null*
	 */
	public Integer getUAnswerCount(User user){
		Long count = Db.queryLong("select count(1) from answer where user_id = ? and del_status =0",  user.get("id"));
		return count == null ? 0 : count.intValue();
	}
	
}
